package ph.edu.ics.sp.graphisched.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.util.ArrayList;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.JTextField;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.jdesktop.application.Application;

import ph.edu.ics.sp.graphisched.Course;
import ph.edu.ics.sp.graphisched.ExcelFilter;
import ph.edu.ics.sp.graphisched.GraphiSchedConstants;
import ph.edu.ics.sp.graphisched.PrintToFile;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
@SuppressWarnings("serial")
public class CreateNewFilePanel extends javax.swing.JPanel implements
		GraphiSchedConstants {
	// private static final FileFilter ExcelFilter = null;
	private JFrame frame;
	private JLabel title;
	private JComboBox semComboBox;
	private JProgressBar loadDataProgress;
	private JComboBox acadYear;
	private JLabel ayLabel;
	private JLabel semLabel;
	private JFileChooser fileChooser;
	private JButton loadData;
	private JButton browseButton;
	private JTextField filePath;
	private JLabel browse;
	private ArrayList<Course> courses = new ArrayList<Course>();
	public static PrintToFile fileToPrint;
	private JButton backButton;
	private boolean isInvokedFromStart = true;

	/**
	 * Auto-generated main method to display this JPanel inside a new JFrame.
	 */
	/*
	 * public static void main(String[] args){ JFrame frame = new JFrame();
	 * frame.getContentPane().add(new GraphiSchedMainPanel());
	 * frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
	 * frame.pack(); frame.setLocation(300, 200); frame.setVisible(true); }
	 */

	public CreateNewFilePanel(JFrame frame, boolean isInvokedFromStart) {
		super();
		this.frame = frame;
		this.isInvokedFromStart = isInvokedFromStart;
		CreateNewFilePanel.fileToPrint = new PrintToFile(frame);
		initGUI();
	}

	/**
	 * Initialize user interface
	 */
	private void initGUI() {
		try {
			this.setPreferredSize(new java.awt.Dimension(352, 222));
			this.setLayout(null);
			{
				title = new JLabel();
				this.add(title);
				title.setBounds(59, 14, 226, 42);
				title.setName("title");
			}
			{
				browse = new JLabel();
				this.add(browse);
				browse.setBounds(22, 109, 318, 14);
				browse.setName("browse");
			}
			{
				filePath = new JTextField();
				this.add(filePath);
				filePath.setBounds(39, 134, 174, 21);
			}
			{
				browseButton = new JButton();
				this.add(browseButton);
				browseButton.setBounds(219, 134, 99, 21);
				browseButton.setName("browseButton");
				browseButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						browseButtonActionPerformed(evt);
					}
				});

			}
			{
				loadData = new JButton();
				this.add(loadData);
				this.add(getSemLabel());
				this.add(getAyLabel());
				this.add(getAcadYear());
				this.add(getLoadDataProgress());
				this.add(getSemComboBox());
				if(isInvokedFromStart){
					this.add(getBackButton());
					loadData.setBounds(167, 167, 116, 21);
				}else{
					int xPos = (frame.getWidth() - 116)/2;
					loadData.setBounds(xPos, 180, 116, 21);
				}
				loadData.setName("loadData");
				loadData.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						loadDataActionPerformed(evt);
					}
				});
			}
			{
				getFileChooser();
			}
			Application.getInstance().getContext().getResourceMap(getClass())
					.injectComponents(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private JFileChooser getFileChooser() {
		ExcelFilter filter = new ExcelFilter();

		if (fileChooser == null) {
			fileChooser = new JFileChooser();
		}

		fileChooser.setFileFilter(filter);

		return fileChooser;
	}

	/**
	 * Browse button action listener: opens an open file dialog to be able to
	 * browse for excel files
	 */
	private void browseButtonActionPerformed(ActionEvent evt) {
		fileChooser.showOpenDialog(frame);
		filePath.setText(null);
		String path = null;
		try {
			path = fileChooser.getSelectedFile().getAbsolutePath();
		} catch (NullPointerException e) {
			
		}
		if(path != null){
			filePath.setText(path);	
		}
	}

	/**
	 * Load Data button action listener: Reads an excel file and stores data to
	 * arraylist of Courses
	 */
	@SuppressWarnings("deprecation")
	private void loadDataActionPerformed(ActionEvent evt) {
		String file = filePath.getText();
		String sem = semComboBox.getSelectedItem().toString();
		fileToPrint.setSemester(sem);
		fileToPrint.setAcadYear(acadYear.getSelectedItem().toString());
		if (file.length() != 0) {
			try {
				String excelFile = file;
				POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(
						excelFile));
				try {
					HSSFWorkbook wb = new HSSFWorkbook(fs);
					HSSFSheet sheet = wb.getSheet("Course List");
					HSSFRow row;

					int rows; // No of rows
					rows = sheet.getPhysicalNumberOfRows();

					int cols = 0; // No of columns
					int tmp = 0;

					// This trick ensures that we get the data properly even if
					// it
					// doesn't start from first few rows
					for (int i = 0; i < 10 || i < rows; i++) {
						row = sheet.getRow(i);
						if (row != null) {
							tmp = sheet.getRow(i).getPhysicalNumberOfCells();
							if (tmp > cols)
								cols = tmp;
						}
					}
					try {
						this.loadDataProgress.setMaximum(rows);
						this.loadDataProgress.setVisible(true);
						row = sheet.getRow(0);
						fileToPrint.setCollege(row.getCell((short) 1)
								.toString().toUpperCase());
						row = sheet.getRow(1);
						fileToPrint.setDepartment(row.getCell((short) 1)
								.toString().toUpperCase());
						// store data in arraylist of courses
						for (int r = 3; r < rows; r++) {
							row = sheet.getRow(r);
							if (row != null) {
								Course course = new Course();
								course.setCourseCode(row.getCell((short) 0)
										.toString());
								course.setCourseTitle(row.getCell((short) 1)
										.toString());
								course.setUnits((int) row.getCell((short) 2)
										.getNumericCellValue());
								course.setSemesterOffered(row
										.getCell((short) 3).toString());
								course.setHasLaboratory((int) row.getCell(
										(short) 4).getNumericCellValue());
								course.setLectureHoursPerWeek((int) row
										.getCell((short) 5)
										.getNumericCellValue());
								course.setLecSessionsPerWeek((int) row.getCell(
										(short) 6).getNumericCellValue());
								course.setLaboratoryHoursPerWeek((int) row
										.getCell((short) 7)
										.getNumericCellValue());
								course.setLaboratorySessionsPerWeek((int) row
										.getCell((short) 8)
										.getNumericCellValue());
								course.setPrerequisite(row.getCell((short) 9)
										.toString());
								course.setCategory(row.getCell((short) 10)
										.toString());
								courses.add(course);
								this.loadDataProgress.setValue(r);
								// this.loadDataProgress.fir
							}
						}

						// sets the frame properties and renders the
						// GraphiSchedTablePanel
						frame.setVisible(false);
						frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
						frame.setLocationRelativeTo(null);
						frame.setContentPane(new GraphiSchedTablePanel(courses,
								frame));
						frame.setVisible(true);
						frame.repaint();
					} catch (Exception ioe) {
						JOptionPane
								.showMessageDialog(
										null,
										"Error occured while loading file!\nPlease check for invalid values in file.",
										"Error", JOptionPane.ERROR_MESSAGE);
					}
				} catch (Exception ioe) {
					JOptionPane
							.showMessageDialog(
									null,
									"Error occured while loading file!\nPlease make sure data sheet is named \"Course List\"",
									"Error", JOptionPane.ERROR_MESSAGE);
				}
			} catch (Exception ioe) {
				JOptionPane.showMessageDialog(null, "File not found!", "Error",
						JOptionPane.ERROR_MESSAGE);
			}

		}
	}

	/**
	 * creates a JLabel which displays the word "Semester"
	 */
	private JLabel getSemLabel() {
		if (semLabel == null) {
			semLabel = new JLabel();
			semLabel.setBounds(46, 72, 69, 14);
			semLabel.setName("semLabel");
		}
		return semLabel;
	}

	private JLabel getAyLabel() {
		if (ayLabel == null) {
			ayLabel = new JLabel();
			ayLabel.setBounds(185, 72, 22, 14);
			ayLabel.setName("ayLabel");
		}
		return ayLabel;
	}

	private JComboBox getAcadYear() {
		if (acadYear == null) {
			ArrayList<String> acadYrs = new ArrayList<String>();
			for (int i = 0; i < NUM_OF_ACAD_YR; i++) {
				StringBuffer ay = new StringBuffer();
				int start = STARTING_YR + i;
				int end = start + 1;
				ay.append(start);
				ay.append("-");
				ay.append(end);
				acadYrs.add(ay.toString());
			}
			ComboBoxModel acadYearModel = new DefaultComboBoxModel(acadYrs
					.toArray());
			acadYear = new JComboBox();
			acadYear.setModel(acadYearModel);
			acadYear.setBounds(213, 69, 89, 21);
		}
		return acadYear;
	}

	private JProgressBar getLoadDataProgress() {
		if (loadDataProgress == null) {
			loadDataProgress = new JProgressBar();
			loadDataProgress.setBounds(72, 202, 205, 14);
			loadDataProgress.setVisible(false);
		}
		return loadDataProgress;
	}

	private JComboBox getSemComboBox() {
		if (semComboBox == null) {
			ComboBoxModel semComboBoxModel = new DefaultComboBoxModel(
					new String[] { "1st", "2nd" });
			semComboBox = new JComboBox();
			semComboBox.setModel(semComboBoxModel);
			semComboBox.setBounds(117, 69, 50, 21);
		}
		return semComboBox;
	}

	private JButton getBackButton() {
		if (backButton == null) {
			backButton = new JButton();
			backButton.setBounds(69, 167, 93, 21);
			backButton.setName("backButton");
			backButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent evt) {
					backButtonActionPerformed(evt);
				}
			});
		}
		return backButton;
	}

	private void backButtonActionPerformed(ActionEvent evt) {
		frame.setContentPane(new GraphiSchedIndexPanel(frame));
		frame.setVisible(true);
		frame.setResizable(false);
		frame.pack();
		frame.setLocationRelativeTo(null);
		frame.repaint();
	}

}
